﻿using YNTK.Common.Core.Manager;
using YNTK.Common.Enum;
using YNTK.Common.Extension;
using YNTK.Common.Filter;
using YNTK.Dependency;
using YNTK.DynamicApiController;
using YNTK.FriendlyException;
using YNTK.SubDev.Interfaces.ZyOaBill;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YNTK.SubDev.Entitys;
using YNTK.SubDev.Entitys.Dto.ZyOaBill;
using Yitter.IdGenerator;
using YNTK.Common.Helper;
using YNTK.JsonSerialization;
using YNTK.System.Interfaces.System;

namespace YNTK.SubDev.ZyOaBill
{
    /// <summary>
    /// 发票信息服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "SubDev",Name = "ZyOaBill", Order = 200)]
    [Route("api/SubDev/[controller]")]
    public class ZyOaBillService : IZyOaBillService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<ZyOaBillEntity> _zyOaBillRepository;
        private readonly IBillRullService _billRuleService;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        /// <summary>
        /// 初始化一个<see cref="ZyOaBillService"/>类型的新实例
        /// </summary>
        public ZyOaBillService(
            ISqlSugarRepository<ZyOaBillEntity> zyOaBillRepository,
            IBillRullService billRuleService,
            IUserManager userManager)
        {
            _zyOaBillRepository = zyOaBillRepository;            
            _db = _zyOaBillRepository.Context;
            _billRuleService = billRuleService;
            _userManager = userManager;
        }

        /// <summary>
        /// 获取发票信息
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<ZyOaBillEntity>().FirstAsync(p => p.Id == id);
            var output = entity.Adapt<ZyOaBillInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取发票信息列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] ZyOaBillListQueryInput input)
        {
            var sidx = input.sidx == null ? "createTime" : input.sidx;
            var data = await _db.Queryable<ZyOaBillEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.customerId), p => p.CustomerId.Equals(input.customerId))
                .WhereIF(!string.IsNullOrEmpty(input.creditCode), p => p.CreditCode.Contains(input.creditCode))
                .Select(it=> new 
                {
                    id = it.Id,
                    customerId=it.CustomerId,
                    creditCode=it.CreditCode,
                    address=it.Address,
                    mobile=it.Mobile,
                    bank=it.Bank,
                    account=it.Account,
                    creater=it.Creater,
                    createTime=it.CreateTime,
                    spare1=it.Spare1,
                }).MergeTable().Select<ZyOaBillListOutput>().OrderBy(sidx+" "+input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return TkPageResult<ZyOaBillListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 新建发票信息
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] ZyOaBillCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            var entity = input.Adapt<ZyOaBillEntity>();
            entity.Id = YitIdHelper.NextId().ToString();
            entity.Creater = _userManager.UserId;
            entity.CreateTime = DateTime.Now;  
            entity.Spare1 = await _billRuleService.GetBillNumber("ZYBILL");
            var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1000);
        }

        /// <summary>
        /// 更新发票信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] ZyOaBillUpInput input)
        {
            var entity = input.Adapt<ZyOaBillEntity>();
            entity.Modifyer = _userManager.UserId;
            entity.ModifyTime = DateTime.Now;  
            var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 删除发票信息
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var entity = await _db.Queryable<ZyOaBillEntity>().FirstAsync(p => p.Id == id);
            _ = entity ?? throw YNTKException.Oh(ErrorCode.COM1005);
            var isOk = await _db.Deleteable<ZyOaBillEntity>().Where(d => d.Id == id).ExecuteCommandAsync();
            if (!(isOk > 0)) throw YNTKException.Oh(ErrorCode.COM1002);
        }
    }
}
